<template>
    <div class="shop-manage">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="fromData" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="页面信息" prop="keywords">
                            <el-input v-model="fromData.keywords" placeholder="请输入页面名称/展示名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="页面状态" prop="status">
                            <el-select v-model="fromData.status" placeholder="" clearable>
                                <el-option label="全部状态" :value="0" />
                                <el-option label="发布" :value="1" />
                                <el-option label="未发布" :value="2" />
                                <el-option label="已停用" :value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-row>
            <el-col class="table-space zw-form-btns">
                <el-button type="primary" @click="router.push('/decorate/add')">新建页面</el-button>
            </el-col>
        </el-row>

        <!-- 表格列表 -->
        <div class="shoptable">
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column label="页面名称" prop="templateName" showOverflowTooltip>
                    <template v-slot="{ row }">
                        <div class="home-page" @click="jumpTo(row)">
                            <div class="template-name">{{ row.templateName }}</div>
                            <img src="@/assets/imgs/mall/decorate/home.png" class="logo" v-if="row.isHomePage == 1" />
                            <img
                                src="@/assets/imgs/mall/decorate/pay-img.png"
                                class="logo"
                                v-if="row.isHomePage == 3" />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="展示名称" prop="templateDesc" showOverflowTooltip>
                    <template v-slot="{ row }">
                        <div v-if="row.templateDesc.length > 8">
                            <el-popover placement="top-start" :width="200" trigger="hover" :content="row.templateDesc">
                                <template #reference>
                                    <div class="one_line">
                                        {{ row.templateDesc }}
                                    </div>
                                </template>
                            </el-popover>
                        </div>
                        <div v-else class="one_line">
                            {{ row.templateDesc || '-' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="页面状态" prop="status">
                    <template v-slot="{ row }">
                        <div class="home-page">
                            <div
                                :style="{
                                    background: row.status == 1 ? '#32D1AD' : row.status == 2 ? '#CCCCCC' : '#FF4A1A'
                                }"
                                class="home-status"></div>
                            <div class="template-name">
                                {{ row.status == 1 ? '已发布' : row.status == 2 ? '未发布' : '已停用' }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="最近修改时间" prop="updatedAt"></el-table-column>
                <!-- <el-table-column label="预览" prop="templateQr" min-width="80">
                    <template v-slot="{ row }">
                        <el-button size="small" @click="previewHandler(row)">二维码</el-button>
                    </template>
                </el-table-column> -->
                <el-table-column class="p16" fixed="right" label="操作" :width="300">
                    <template v-slot="scope">
                        <el-button
                            class="allBtn"
                            @click="router.push('/decorate/add?pageId=' + scope.row.id)"
                            size="small"
                            v-auth="'banner:edit'"
                            >编辑</el-button
                        >
                        <el-button
                            size="small"
                            class="allBtn"
                            :ref="el => setItemRef(el, `spear${scope.row.id}`)"
                            v-auth="'seckill_list:spread'"
                            v-if="scope.row.status == 1 && scope.row.isHomePage != 3"
                            @click="promote(scope.row)">
                            推广
                        </el-button>
                        <!-- <el-dropdown v-if="isShowMore" @command="handleCommand($event, scope.row)">
                            <el-button v-if="isShowMore" size="small" style="margin-left: 8px; margin-top: 1px"
                                >更多</el-button
                            >
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        v-if="scope.row.status == 1 && hasPermissions('banner:edit')"
                                        command="copy"
                                        >复制</el-dropdown-item
                                    >
                                    <el-dropdown-item
                                        v-if="scope.row.isHomePage == 2 && hasPermissions('banner:sethome')"
                                        command="home"
                                        >设为首页</el-dropdown-item
                                    >
                                    <el-dropdown-item
                                        v-if="
                                            scope.row.status == 1 &&
                                            scope.row.isHomePage == 2 &&
                                            hasPermissions('banner:publish')
                                        "
                                        command="disabled"
                                        >停用</el-dropdown-item
                                    >
                                    <el-dropdown-item
                                        v-if="
                                            (scope.row.status == 2 ||
                                                (scope.row.status == 3 && scope.row.isHomePage == 2)) &&
                                            hasPermissions('banner:publish')
                                        "
                                        command="release"
                                        >发布</el-dropdown-item
                                    >
                                    <el-dropdown-item
                                        v-if="
                                            scope.row.status !== 1 &&
                                            scope.row.isHomePage == 2 &&
                                            hasPermissions('banner:publish')
                                        "
                                        command="remove"
                                        >删除</el-dropdown-item
                                    >
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown> -->

                        <el-button
                            @click="copy(scope.row)"
                            size="small"
                            v-auth="'banner:edit'"
                            v-if="scope.row.isHomePage != 3"
                            class="allBtn"
                            >复制</el-button
                        >
                        <el-button
                            v-if="scope.row.isHomePage == 2"
                            size="small"
                            class="allBtn"
                            @click="operate(3, scope.row.id)"
                            v-auth="'banner:sethome'"
                            >设为首页</el-button
                        >
                        <el-button
                            v-if="scope.row.status == 1 && scope.row.isHomePage == 2"
                            size="small"
                            class="allBtn"
                            @click="operate(2, scope.row.id)"
                            v-auth="'banner:publish'"
                            >停用</el-button
                        >
                        <el-button
                            v-if="
                                (scope.row.status == 2 && scope.row.isHomePage != 3) ||
                                (scope.row.status == 3 && scope.row.isHomePage == 2)
                            "
                            size="small"
                            class="allBtn"
                            @click="operate(1, scope.row.id)"
                            v-auth="'banner:publish'"
                            >发布</el-button
                        >
                        <el-button
                            v-if="scope.row.status !== 1 && scope.row.isHomePage == 2"
                            size="small"
                            class="allBtn"
                            @click="del(scope.row)"
                            v-auth="'banner:publish'"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="zw-pagination">
            <PaginationVue
                :pageSize="page.perPage"
                :currentPage="page.page"
                :total="total"
                @sizeChange="sizeChange"
                @pageChange="pageChange">
            </PaginationVue>
        </div>
        <el-dialog v-model="dialogVisible" title="复制一个页面" width="30%" @close="handleClose">
            <el-form ref="formPageRef" :model="formPage" label-width="auto" :rules="rules">
                <el-form-item label="页面名称" prop="templateName" required>
                    <el-input
                        v-model="formPage.templateName"
                        placeholder="仅用于后台展示，不超过30个字"
                        maxlength="30"
                        show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <template #footer
                ><el-button plain @click="cancel">取消</el-button
                ><el-button type="primary" @click="submit">确定</el-button>
            </template>
        </el-dialog>
        <el-popover
            placement="top"
            width="400"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            virtual-triggering
            trigger="click"
            :visible="popoverVisible"
            popper-class="custom-popover-decorate not-close">
            <SpreadBox
                v-if="popoverVisible"
                :path="path"
                :params="params"
                :downloadName="downloadName"
                :popoverFn="popoverVisibleHandler" />
        </el-popover>
    </div>
</template>
<script setup>
import { nextTick, reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/request';
import storage from '@/commons/storage';
import PaginationVue from '@/components/Pagination.vue';
import useClipboard from 'vue-clipboard3';
import { getUuid, downloadImgHandler } from '@/commons/utils';
import ElemBox from '@/commons/element/message.js';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import SpreadBox from '@/components/SpreadBox.vue';
import store from '@/store/index';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isShowMore = computed(() => {
    return permissions.has('banner:edit') || permissions.has('banner:sethome') || permissions.has('banner:publish');
});
const hasPermissions = val => {
    return permissions.has(val);
};

const formRef = ref();
const formPageRef = ref();
const router = useRouter();
const fromData = reactive({ keywords: '', status: 0 });
const page = reactive({ perPage: 10, page: 1 });
let dialogVisible = ref(false);
// let qrType = ref(1);
let pageLink = ref('/pages-activity/dynamic/index?id=');
const total = ref(0);
// const qrCodeUrl = ref('');
// let templateDesc = ref('');
// let openPopoverId = ref('');
let rowData = reactive({});
const formPage = reactive({ templateName: '' });

const rules = reactive({
    templateName: [{ required: true, message: '页面名称不能为空' }]
});
const tableData = ref([
    {
        id: 1,
        tenantId: 1,
        shopId: 1,
        templateDesc: '',
        templateName: '',
        status: 1,
        isHomePage: 1,
        createdAt: '',
        updatedAt: ''
    }
]);
const initPage = () => {
    request('decorateListServ', { ...page, ...fromData }).then(res => {
        total.value = res.data.totalCount;
        tableData.value = res.data.list || [];
    });
};
initPage();
const operate = (index, id) => {
    if (index == 3) {
        //设为首页
        ElemBox.ElMessageBoxPromise(
            `设为首页后，当前页面内容将替换原有首页。设置后不可撤销，确定要将该页面设为首页吗？`
        ).then(res => {
            request('setHomeServ', { templateId: id, isHome: 1 }).then(res => {
                ElMessage.success(`设置成功`);
                initPage();
            });
        });
    } else {
        ElemBox.ElMessageBoxPromise(
            `${index == 2 ? '停用后，用户将无法查看该页面。确定要停用吗？' : '确定要发布吗？'}`
        ).then(res => {
            request('homePubServ', { templateId: id, isEnable: index }).then(res => {
                ElMessage.success(`${index == 2 ? '停用' : '发布'}成功`);
                initPage();
            });
        });
    }
};
/**
 * 切换页码
 * @param {*} data
 */
const pageChange = data => {
    page.page = data;
    initPage();
};
/**
 * 切换每页展示条数
 * @param {*} data
 */
const sizeChange = data => {
    page.perPage = data;
    page.page = 1;
    initPage();
};

/**
 * 预览
 */
const jumpTo = row => {
    window.open(location.origin + `/decorate/add?pageId=${row.id}&type=preview&isHomePage=${row.isHomePage}`);
};
/**
 * 清空
 */
const resetHandler = () => {
    page.page = 1;
    formRef.value.resetFields();
    initPage();
};
/**
 * 复制
 */
const copyHandler = async () => {
    const { toClipboard } = useClipboard();
    try {
        await toClipboard(pageLink.value);
        ElMessage.success('复制成功');
    } catch (e) {}
};
/**
 * 搜索
 */
const searchHandler = () => {
    page.page = 1;
    initPage();
};
/**删除*/
const del = row => {
    request('templateDel', { id: row.id }).then(res => {
        ElMessage.success(`删除成功`);
        initPage();
    });
};
/**复制 */
const copy = row => {
    dialogVisible.value = true;
    rowData = row;
};
const handleCommand = (command, row) => {
    if (command == 'copy') {
        dialogVisible.value = true;
        rowData = row;
        return;
    }
    if (command == 'home') {
        //设为首页
        ElemBox.ElMessageBoxPromise(
            `设为首页后，当前页面内容将替换原有首页。设置后不可撤销，确定要将该页面设为首页吗？`
        ).then(res => {
            request('setHomeServ', { templateId: row.id, isHome: 1 }).then(res => {
                ElMessage.success(`设置成功`);
                initPage();
            });
        });
        return;
    }
    if (['disabled', 'release'].includes(command)) {
        ElemBox.ElMessageBoxPromise(
            `${command == 'disabled' ? '停用后，用户将无法查看该页面。确定要停用吗？' : '确定要发布吗？'}`
        ).then(res => {
            request('homePubServ', { templateId: row.id, isEnable: command == 'disabled' ? 2 : 1 }).then(res => {
                ElMessage.success(`${command == 'disabled' ? '停用' : '发布'}成功`);
                initPage();
            });
        });
        return;
    }
    if (command == 'remove') {
        request('templateDel', { id: row.id }).then(res => {
            ElMessage.success(`删除成功`);
            initPage();
        });
        return;
    }
};
const popoverVisibleHandler = () => {
    popoverVisible.value = false;
};
// todo:推广页
let path = ref();
let params = ref();
let downloadName = ref();
const promote = row => {
    if (row.isHomePage == 1) {
        path.value = 'pages/tabbar/home';
        params.value = `shopId=${storage.get('ZW-SHOPID')}`;
    } else {
        path.value = 'pages-activity/dynamic/index';
        params.value = `id=${row.id}&shopId=${storage.get('ZW-SHOPID')}`;
    }
    downloadName.value = row?.templateName;
    // templateDesc.value = row?.templateDesc;
    buttonRef.value = itemRefs['spear' + row.id];
    // openPopoverId.value = row.id;
    nextTick(() => {
        popoverVisible.value = true;
    });
};
const cancel = () => {
    dialogVisible.value = false;
    formPage.templateName = '';
    formPageRef.value.resetFields();
};
const handleClose = () => {
    cancel();
};
const submit = () => {
    formPageRef.value.validate(async valid => {
        if (valid) {
            var param = rowData;
            param.isHomePage = 2;
            delete param.id;
            param.pageCode = getUuid();
            param.templateName = formPage.templateName;
            param.components = JSON.parse(param.components);
            request('decorateServ', param).then(res => {
                initPage();
                cancel();
            });
        }
    });
};

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null, status: null });
// 点击popover外部
// const onClickOutside = el => {
//     qrType.value = 1;
//     // buttonRef.value = null;
//     // templateDesc.value = null;
//     popoverVisible.value = false;
//     // openPopoverId.value = '';
// };
</script>
<style lang="scss">
.custom-popover-decorate {
    padding: 0 !important;
    &-main {
        padding: 16px;
    }
}
</style>
<style lang="scss" scoped>
.one_line {
    overflow: hidden; // 溢出隐藏
    white-space: nowrap; // 强制一行
    text-overflow: ellipsis;
}
.title {
    padding-bottom: 12px;
}
.el-input {
    width: 220px;
}
.custom-preview {
    margin: 16px 0;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
}
.table-space {
    margin: 18px 0;
}
.shop-manage {
    :deep {
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
            .el-button--small {
                width: 80px;
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
                border: 1px solid #eaeaea;
            }
            .el-button--small {
                margin: 4px;
            }
        }
        .el-table .el-table__cell {
            padding: 20px 0;
        }

        .el-table th.el-table__cell {
            padding: 12px 0;
        }

        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
        td.el-table-fixed-column--right {
            padding: 16px 0 !important;
        }
    }
}
.shoptable {
    .allBtn {
        /* min-width: 80px; */
    }
    .home-page {
        display: flex;
        align-items: center;
        cursor: pointer;
        .home-status {
            width: 8px;
            height: 8px;
            background: #ff4a1a;
            border-radius: 4px;
            margin-right: 4px;
        }
        .template-name {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #ff6b00;
        }
        .logo {
            width: 16px;
            height: 16px;
            margin-left: 4px;
        }
    }
    .code {
        text-decoration: underline;
        color: #ff6b00;
    }
}
.zw-qrcode {
    display: flex;
    flex-direction: row;
    justify-content: center;
}
</style>
